<template>
  <div style="min-width: 1200px">
    <div v-if="$route.path == '/itemAnalyse'">
      <div class="vs-search-box">
        <div class="vs-search-title">客户来源分析</div>
        <el-form ref="form" :inline="true" :model="paging" label-width="120px">
          <el-form-item label="门店">
            <el-select v-model="paging.store_id" placeholder="请选择">
              <el-option label="全部" :value="0"> </el-option>
              <el-option
                v-for="item in shopList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期：">
            <el-date-picker
              @change="setDate"
              v-model="value1"
              value-format="yyyy-MM-dd"
              style="width: 250px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" class="vs-right-btns">
            <el-button @click="handleCurrentChange(1)" type="primary"
              >查询</el-button
            >
            <el-button icon="el-icon-download" @click="derive" :loading="isDerive">导出</el-button>
          </el-form-item>
        </el-form>
        <div
          ref="customerSource"
          style="width: 100%; height: 400px"
          class="total-number-tu"
        ></div>
      </div>
      <div class="vs-search-box">
        <div class="vs-search-title">消费项目分析</div>
        <el-form ref="form" :inline="true" :model="paging" label-width="120px">
          <el-form-item label="门店">
            <el-select v-model="pagin.store_id" placeholder="请选择">
              <el-option label="全部" :value="0"> </el-option>
              <el-option
                v-for="item in shopList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期：">
            <el-date-picker
              @change="setDate2"
              v-model="value2"
              value-format="yyyy-MM-dd"
              style="width: 250px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" class="vs-right-btns">
            <el-button @click="handleCurrentChange(2)" type="primary"
              >查询</el-button
            >
            <el-button icon="el-icon-download" @click="derive2" :loading="isDerive2">导出</el-button>
          </el-form-item>
        </el-form>
        <el-checkbox-group
          v-model="checkboxGroup1"
          size="medium"
          class="select-top"
        >
          <div class="poiu">
            <el-button
              :type="
                checkboxGroup1.length > 0 &&
                checkboxGroup1.length == projectId.length
                  ? 'primary'
                  : ''
              "
              class="poi"
              @click="all(1)"
              >全部</el-button
            >
          </div>
          <el-checkbox-button
            v-for="item in getJects"
            :label="item.id"
            :key="item.id"
            >{{ item.name }}</el-checkbox-button
          >
        </el-checkbox-group>
        <div class="flex">
          <div
            ref="consume"
            style="width: 60%; height: 400px"
            class="total-number-tu"
          ></div>
          <div
            ref="consumeGender"
            style="width: 40%; height: 400px"
            class="total-number-tu"
          ></div>
        </div>
      </div>
      <div class="vs-search-box">
        <div class="vs-search-title" >各性别所做项目比例</div>
        <el-form ref="form" :inline="true" :model="paging" label-width="120px">
          <el-form-item label="门店">
            <el-select v-model="pagi.store_id" placeholder="请选择">
              <el-option label="全部" :value="0"> </el-option>
              <el-option
                v-for="item in shopList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期：">
            <el-date-picker
              @change="setDate3"
              v-model="value3"
              value-format="yyyy-MM-dd"
              style="width: 250px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" class="vs-right-btns">
            <el-button @click="handleCurrentChange(3)" type="primary"
              >查询</el-button
            >
            <el-button icon="el-icon-download" @click="derive3" :loading="isDerive3">导出</el-button>
          </el-form-item>
        </el-form>
        <el-checkbox-group
          v-model="checkboxGroup2"
          size="medium"
          class="select-top"
        >
          <div class="poiu">
            <el-button
              :type="
                checkboxGroup2.length > 0 &&
                checkboxGroup2.length == projectId.length
                  ? 'primary'
                  : ''
              "
              class="poi"
              @click="all(2)"
              >全部</el-button
            >
          </div>
          <el-checkbox-button
            v-for="item in getJects"
            :label="item.id"
            :key="item.id"
            >{{ item.name }}</el-checkbox-button
          >
        </el-checkbox-group>
        <div
          ref="ratio"
          style="width: 100%; height: 400px"
          class="total-number-tu"
        ></div>
      </div>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value1: "",
      value2: "",
      value3: "",
      isread: 0,
      search: "",
      checkboxGroup1: [],
      checkboxGroup2: [],
      loading: false,
      loading2: false,
      isBtn: false,
      isInfo: false,
      dialogVisible: false,
      form: {
        username: "",
        date: "",
      },
      paging: {
        store_id: 0,
        username: "", //姓名
        start_time: "", //开始时间
        end_time: "", //结束时间
        page: 1,
        total: 0,
        limit: 10,
      },
      pagin: {
        store_id: 0,
        username: "", //姓名
        start_time: "", //开始时间
        end_time: "", //结束时间
        page: 1,
        total: 0,
        limit: 10,
      },
      pagi: {
        store_id: 0,
        username: "", //姓名
        start_time: "", //开始时间
        end_time: "", //结束时间
        page: 1,
        total: 0,
        limit: 10,
      },
      anal: {
        store_id: 0,
        start_time: "",
        end_time: "",
      },
      getJect: {
        name: "",
        cate_id: "",
        id: "",
      },
      consume: {
        store_id: 0,
        start_time: "",
        end_time: "",
        project_ids: "",
      },
      sexualityAnalyze: {
        store_id: 0, //门店id 全部传0
        start_time: "", //开始时间 年-月-日
        end_time: "", //结束时间 年-月-日
        project_ids: "", //项目id 多个用逗号拼接 全部传0
      },
      form: {
        date: "",
      },
      shopList: [], //获取门店信息
      analData: [], //客户来源
      consumeData: [], //消费项目
      consumesData: [], //消费项目
      sexualityAnal: [], //各性别所做项目分析
      getJects: [], //项目列表/详情
      tableData: [],
      test: [], //个别项目图时间
      usera: [],
      mans: [],
      womans: [],
      projectId: [],
      arrDatas:[],
      mwCombined:[],
      custCombined:[],
      isDerive:false,
      isDerive2:false,
      isDerive3:false,
      clientWidth:0,
    };
  },
  async created() {
    let date1 = this.getCurrentMonthFirst();
    let date2 = this.getCurrentMonthLast();
    this.anal.start_time = date1;
    this.anal.end_time = date2;
    this.consume.start_time = date1;
    this.consume.end_time = date2;
    this.sexualityAnalyze.start_time = date1;
    this.sexualityAnalyze.end_time = date2;
    this.anal.store_id = 0;
    this.consume.store_id = 0;
    this.sexualityAnalyze.store_id = 0;
    await this.getProjects();
    await this.getData();
    await this.getConsumption();
    await this.getGenderProject();
    // 页面日期赋值
    this.value1 = [date1, date2];
    this.value2 = [date1, date2];
    this.value3 = [date1, date2];
  },
  async mounted() {
      this.clientWidth = document.body.clientWidth;
    await this.homegetStore(); //获取门店
    await this.getProjects(); //获取项目详情
  },
  methods: {
      //客户来源分析导出
      async derive(){
            this.isDerive = true;
            let res = await this.$Http.exportProjectSource(this.anal);
            this.utils.downloadXlsx(res,'客户来源分析')
            this.isDerive = false;
        },
      //消费项目分析导出
      async derive2(){
            this.isDerive2 = true;
            let res = await this.$Http.exportProjectConsume(this.consume);
            this.utils.downloadXlsx(res,'消费项目分析')
            this.isDerive2 = false;
        },
      //个性别所做项目比例导出
      async derive3(){
            this.isDerive3 = true;
            let res = await this.$Http.exportGenderProject(this.sexualityAnalyze);
            this.utils.downloadXlsx(res,'个性别所做项目比例')
            this.isDerive3 = false;
        },

    async homegetStore() {
      //获取门店
      let { code, data } = await this.$Http.homegetStore();
      if (code) {
        this.shopList = data;
        console.log(998877, this.shopList);
      }
    },

    setDate(e) {
      //获取时间
      this.anal.start_time = e[0];
      this.anal.end_time = e[1];
      console.log(this.paging,"this.pagingthis.paging")
    },

    setDate2(e) {
      //获取时间
      console.log("setData", e);
      this.consume.start_time = e[0];
      this.consume.end_time = e[1];
    },

    setDate3(e) {
      //获取时间
      console.log("setData", e);
      this.sexualityAnalyze.start_time = e[0];
      this.sexualityAnalyze.end_time = e[1];
    },

    getCurrentMonthFirst() {
      //获取当月第一天的值
      var date = new Date();
      date.setDate(1);
      var month = parseInt(date.getMonth() + 1);
      var day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + day;
    },

    getCurrentMonthLast() {
      //获取当月最后一天的值
      var date = new Date();
      var currentMonth = date.getMonth();
      var nextMonth = ++currentMonth;
      var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      var oneDay = 1000 * 60 * 60 * 24;
      var lastTime = new Date(nextMonthFirstDay - oneDay);
      var month = parseInt(lastTime.getMonth() + 1);
      var day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + day;
    },

    async getProjects() {
      //项目列表/详情
      this.loading = true;
      let { code, data } = await this.$Http.getProject(this.getJect);
      if (code) {
        this.loading = false;
        this.getJects = data.data;
        console.log(777777777, this.getJects);
      }
      let ids = [];
      this.getJects.forEach((item) => {
        ids.push(item.id);
      });
        this.projectId = ids;
        this.checkboxGroup1 = ids
        this.checkboxGroup2 = ids
      console.log(43243243243, this.projectId);
    },

    async getData() {
      //客户来源分析
      this.loading = true;
      this.anal.store_id = this.paging.store_id;
    //   this.anal.start_time = this.paging.start_time;
    //   this.anal.end_time = this.paging.end_time;
      let { code, data } = await this.$Http.getProjectSource(this.anal);
      if (code) {
        this.loading = false;
        for (let key in data) {
            if(data[key]<=0)data[key]=null;
        }
        this.analData = data;
        this.custCombined = this.analData.comment_count+this.analData.applet_count+this.analData.phone_count+this.analData.butler_count+this.analData.tourist_count
        console.log(88888999999,this.custCombined);
        this.init1();
      }
    },

    async getConsumption() {
      //消费项目数据
      console.log(4444444444, this.checkboxGroup1);
      this.consume.project_ids = this.checkboxGroup1;
      this.consume.store_id = this.pagin.store_id;
    //   this.consume.start_time = this.pagin.start_time;
    //   this.consume.end_time = this.pagin.end_time;
      this.loading = true;
      let { code, data } = await this.$Http.getProjectConsume(this.consume);
      if (code) {
        this.loading = false;
        this.consumeData = data.gender;
        this.consumesData = data.project ? data.project : [];
        this.mwCombined = this.consumeData.man + this.consumeData.woman
        console.log(456654,this.mwCombined);
        this.init2();
      }
    },

    async getGenderProject() {
      //个性别所做项目比例
      console.log(6666666666, this.checkboxGroup1);
      this.sexualityAnalyze.project_ids = this.checkboxGroup2;

      this.sexualityAnalyze.store_id = this.pagi.store_id;
    //   this.sexualityAnalyze.start_time = this.pagi.start_time;
    //   this.sexualityAnalyze.end_time = this.pagi.end_time;

      console.log(
        "log111111111111",
        this.sexualityAnalyze.start_time,
        this.sexualityAnalyze.end_time
      );
      this.loading = true;
      let { code, data } = await this.$Http.getGenderProject(
        this.sexualityAnalyze
      );
      if (code) {
        this.loading = false;
        this.sexualityAnal = data;
        console.log("sexualityAnal", this.sexualityAnal);
      }
      let daye = [];
      let man = [];
      let woman = [];
      this.sexualityAnal.forEach((item) => {
        let womendata = [];
        womendata.push(item.day);
        womendata.push(item.user.woman);
        woman.push(womendata);
        daye.push(item.day);

        let mendata = [];
        mendata.push(item.day);
        mendata.push(item.user.man);
        man.push(mendata);
      });
      this.test = daye;
      this.mans = man;
      this.womans = woman;
      this.init3();
    },

    async init1() {
      //绘制第一个图表

      //客户来源分析
      let customerSource = this.$echarts.init(this.$refs.customerSource); //第一个图表
      customerSource.setOption({
        title: {
          show: false,
          // text: '同名数量统计',
          // subtext: '纯属虚构',
          // left: 'center'
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} :{c} ({d}%)",
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          x: "60%",
          y: "center",
          // data: data.legendData,
          // selected: data.selected
        },
        series: [
          {
            name: "客户来源分析",
            type: "pie",
            radius: "70%",
            center: ["40%", "50%"],
            data: [
              { value: this.analData.tourist_count, name: "散客" },
              { value: this.analData.comment_count, name: "大众点评" },
              { value: this.analData.applet_count, name: "小程序" },
              { value: this.analData.phone_count, name: "电话" },
              { value: this.analData.butler_count, name: "管家微信" },
            ],
            label: {
              normal: {
                //数据为0时饼状图不显示为0的数据
                // formatter: '{d}%',
                formatter:(params)=>{
                  if (params.value > 0) {
                    let num = (params.value*100/this.custCombined)
                    num = num.toFixed(2)
                    return `${params.data.name}\n${num}%(${params.value})`
                  } else {
                    return "";
                  }
                },
                // position: 'inside'
              },
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
    },
    async init2() {
      //绘制第二个图表
      // 消费项目分析
      let consume = this.$echarts.init(this.$refs.consume);
      let arrData = [];
      //循环遍历得到图的数值和名称
      this.consumesData.forEach((el, i) => {
        let item = {
          value: el.count<=0?null:el.count, //获取value数值
          name: el.name, //获取名字
          percent:el.ratio//获取百分比
        };
        arrData.push(item);
        // this.arrDatas = arrData
        // console.log(888888888888,this.arrDatas);
      });
      consume.setOption({
        title: {
          show: false,
          // text: '同名数量统计',
          // subtext: '纯属虚构',
          // left: 'center'
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%) ",
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          // left:50
          right: 10,
          // x:'80%',
          padding: 30,
          y: "center",
          // data: data.legendData,
          // selected: data.selected
        },
        series: [
          {
            name: "消费项目分析",
            type: "pie",
            radius: this.clientWidth > 1500 ?'70%':"50%",
            center: ["40%", "50%"],
            data: arrData,
            label: {
              normal: {
                //数据为0时饼状图不显示为0的数据
                // formatter: "{c}",
                formatter: function (params) {
                  if (params.value > 0) {
                    return `${params.data.name}\n${params.percent}%(${params.value})`;
                  } else {
                    return "";
                  }
                },
                // position: "inside",
              },
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
      let consumeGender = this.$echarts.init(this.$refs.consumeGender);
      consumeGender.setOption({
        title: {
          show: false,
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        color: ["#FFFF80", "#EC808D"],
        legend: {
          type: "scroll",
          orient: "vertical",
          // left:50,
          right: 0,
          // x:'20%',
          y: "center",
          // data: data.legendData,
          // selected: data.selected
        },
        series: [
          {
            name: "客户来源分析",
            left:30,
            type: "pie",
            radius: this.clientWidth > 1600 ?'60%':"50%",
            center: ["50%", "50%"],
            data: [
              { value: this.consumeData.man, name: "男" },
              { value: this.consumeData.woman, name: "女" },
            ],
            label: {
              normal: {
                // formatter: "{c}",
                formatter:(params)=>{
                  if (params.value > 0) {
                    let num = (params.value*100/this.mwCombined)
                    num = num.toFixed(2)
                    return `${params.data.name}\n${num}%\n(${params.value})`
                  } else {
                    return "";
                  }
                },
                // position: "inside",
              },
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
    },
    async init3() {
      //绘制第三个图表
      //各性别所做项目比例
      let ratio = this.$echarts.init(this.$refs.ratio);
      ratio.setOption({
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "3%",
          bottom: "3%",
          containLabel: true,
        },
        legend: {
          right: 0,
          orient: "vertical",
          y: "center",
          data: ["男", "女"],
        },
        xAxis: {
          type: "category",
          min: this.sexualityAnalyze.start_time,
          max: this.sexualityAnalyze.end_time,
          axisLabel: {
            interale: 0,
            rotate: 0, //设置日期显示样式（倾斜度）
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            show: true,
            interval: "auto",
            formatter: "{value} %",
          },
        },
        series: [
          {
            name: "男",
            type: "line",
            // stack: '人数',
            data: this.mans,
          },
          {
            name: "女",
            type: "line",
            // stack: '人数',
            data: this.womans,
          },
        ],
      });
      window.onresize = function () {};
    },
    async setRow(type, row) {
      this.utils.goUrl("/goodsInfo?type=" + type);
    },
    handleClose(dom) {
      this.$refs["ruleForm"].resetFields();
      this.dialogVisible = false;
      dom && dom();
    },

    reset() {
      //重置
      this.paging = this.$options.data().paging;
      this.form.date = "";
      this.handleCurrentChange(1);
    },
    all(val) {
      if (val == 1) {
        if (this.checkboxGroup1.length == this.projectId.length) {
          this.checkboxGroup1 = [];
        } else {
          this.checkboxGroup1 = this.projectId;
        }
      }
      if (val == 2) {
        if (this.checkboxGroup2.length == this.projectId.length) {
          this.checkboxGroup2 = [];
        } else {
          this.checkboxGroup2 = this.projectId;
        }
      }
    },
    handleSizeChange(val) {
      this.paging.limit = val;
      this.repairGetList();
    },
    handleCurrentChange(val) {
      if (val == 1) {
        this.getData();
      }
      if (val == 2) {
        this.getConsumption();
      }
      if (val == 3) {
        this.getGenderProject();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.image-thumbnail {
  width: 130px;
  height: 130px;
}
.select-top {
  margin-left: 50px;
}
.poiu {
  // float: left;
  height: 35px;
}
.poi {
  height: 35px;
}
</style>